package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.*;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public Result orderInfor(ReserveInfor reserveInfor) {
        //得到电话号码和生份证号，去会员表中查询是否是已经注册的会员
        String telephone = reserveInfor.getTelephone();
        String idCard = reserveInfor.getIdCard();
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getPhoneNumber, telephone);
        Member member = memberMapper.selectOne(wrapper);
        //注册用户信息补充
        if (member != null) {
            member.setPhoneNumber(telephone);
            member.setIdCard(idCard);
            member.setSex(reserveInfor.getSex());
            member.setName(reserveInfor.getName());
            memberMapper.updateById(member);
        }
        //根据会员id查询是否已经预约
        LambdaQueryWrapper<Order> wrapper1=new LambdaQueryWrapper<>();
        wrapper1.eq(Order::getMemberId,member.getId()).eq(Order::getSetmealId, reserveInfor.getSetmealId());
        Order order1 = orderMapper.selectOne(wrapper1);
        if(order1!=null){
            return new Result(false,"你已经预约了该项套餐，请勿重复");
        }
        //根据会员id将预约信息添加到预约表中去
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderStatus("未到诊");
        order.setOrderType("电话预约");
        order.setSetmealId(reserveInfor.getSetmealId());
        order.setOrderDate(reserveInfor.getOrderDate());
        orderMapper.insert(order);
        Integer orderId = order.getId();
        return new Result(true,"用户预约成功",orderId);
    }

    @Override
    public Result findById(Integer id) {
        //根据预约查询预约对象信息
        Order order = orderMapper.selectById(id);
        //查询会员id
        Integer memberId = order.getMemberId();
        //查询会员信息
        Member member = memberMapper.selectById(memberId);
        //会员姓名
        String name = member.getName();
        //套餐id
        Integer setmealId = order.getSetmealId();
        Setmeal setmeal = setmealMapper.selectById(setmealId);
        //套餐姓名
        String setmealName = setmeal.getName();
        OrderInfor orderInfor=new OrderInfor();
        orderInfor.setMember(name);
        orderInfor.setSetmeal(setmealName);
        orderInfor.setOrderType(order.getOrderType());
        orderInfor.setOrderDate(order.getOrderDate());
        return new  Result(true,"查询成功",orderInfor);
    }
}

